<script setup lang="ts">
import usePeople from '@renderer/composables/usePeople'
import formButton from '@renderer/components/formButton.vue'
import { ref, reactive } from 'vue'
import dayjs from 'dayjs'
import { Action, ElMessageBox, type CascaderProps, type CascaderValue, ElMessage } from 'element-plus'
import NavBar from '@renderer/components/navBar.vue'
import uploadAvatarImage from '@renderer/components/uploadAvatarImage.vue'
const initParams = () => ({
  type: '',
  cate_name: '',
  page: 1,
  limit: 10,
})
const initsubmitForm = () => ({
  avatar: 'https://cw3.obs.cn-north-4.myhuaweicloud.com/default/avatar.png',
  name: '',
  type: '',
  cate_name: '',
  phone: '',
  id_card: '',
  exigency_name: '',
  exigency_phone: '',
  wechat: '',
  alipay: '',
  bank_name: '',
  bank_no: '',
  bank_person: '',
  bank_sub: '',
  work_time: '',
  remark: '',
  cooperation_person: '',
})
const queryParams = reactive(initParams())
const submitForm = ref(initsubmitForm())
const ids = ref([])
const peopleDialog = ref(false)
const currentType = ref<initType>('init')
const dialogType = ref('add')
const staffName = ref('')
const showTime = ref('')
const peopleStaffName = ref<string[]>([''])
const staffProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level, data } = node
    setTimeout(async () => {
      let nodes
      switch (level) {
        case 0:
          nodes = [
            {
              value: '',
              label: '全部',
              leaf: true,
            },
            {
              value: '供应商',
              label: '供应商',
              leaf: level >= 1,
            },
            {
              value: '工班组',
              label: '工班组',
              leaf: level >= 1,
            },
          ]
          break
        case 1:
          const cateList = await getDisbursePersonCate({
            type: data?.label,
          })
          if (cateList.length) {
            nodes = cateList.map((item) => ({
              value: item.name,
              label: item.name,
              leaf: level >= 1,
            }))
          }
          nodes.unshift({
            value: '',
            label: '全部',
            leaf: level >= 1,
          })
          break
      }
      resolve(nodes)
    }, 1000)
  },
} as CascaderProps
const peopleStaffProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { level, data } = node
    setTimeout(async () => {
      let nodes
      switch (level) {
        case 0:
          nodes = [
            {
              value: '供应商',
              label: '供应商',
              leaf: level >= 1,
            },
            {
              value: '工班组',
              label: '工班组',
              leaf: level >= 1,
            },
          ]
          break
        case 1:
          const cateList = await getDisbursePersonCate({
            type: data?.label,
          })
          if (cateList.length) {
            nodes = cateList.map((item) => ({
              value: item.name,
              label: item.name,
              leaf: level >= 1,
            }))
          }
          break
      }
      resolve(nodes)
    }, 1000)
  },
} as CascaderProps
const change = (value: CascaderValue) => {
  if (value[0] == '') {
    queryParams.cate_name = ''
    queryParams.type = ''
  } else {
    queryParams.cate_name = value[1]
    queryParams.type = value[0]
  }
}
const peopleChange = (value: CascaderValue) => {
  queryParams.cate_name = value[1]
  queryParams.type = value[0]
}
const handleQuery = async () => {
  currentType.value = 'search'
  await initData(currentType.value, 1)
}
const handleReset = async () => {
  Object.assign(queryParams, initParams())
  currentType.value = 'init'
  staffName.value = ''
  await initData('init', 1)
}
const handleAddPeople = () => {
  dialogType.value = 'add'
  peopleDialog.value = true
}
const handleClose = async () => {
  Object.assign(submitForm.value, initsubmitForm())
  showTime.value = ''
  peopleStaffName.value = ['']
  peopleDialog.value = false
  await initData('init', 1)
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
}
const handleTimeChange = (val) => {
  submitForm.value.work_time = dayjs(val).unix() + ''
}
const handleAvatar = (url: string) => {
  submitForm.value.avatar = url
}
const handleSubmit = async () => {
  if (!submitForm.value.avatar) {
    ElMessage.error('头像不能为空')
    return
  }
  if (!submitForm.value.name) {
    ElMessage.error('名称不能为空')
    return
  }
  if (!peopleStaffName) {
    ElMessage.error('身份工种不能为空')
    return
  }
  if (!submitForm.value.phone) {
    ElMessage.error('手机号不能为空')
    return
  }
  if (dialogType.value == 'add') {
    if (await addDisbursePerson(submitForm.value)) {
      await handleClose()
    }
  } else {
    if (await updateDisbursePerson(submitForm.value)) {
      await handleClose()
    }
  }
}
const handleEditPeople = async (id: number) => {
  const userInfo = await getDisbursePersonDetail({ id })
  submitForm.value = userInfo
  peopleStaffName.value = [userInfo.type, userInfo.cate_name]
  showTime.value = userInfo.work_time ? dayjs.unix(userInfo.work_time).format('YYYY-MM-DD') : ''
  dialogType.value = 'edit'
  peopleDialog.value = true
}
const handleNextPage = async (val: number) => {
  await initData(currentType.value, val)
}
const handleDelPeople = (id: number) => {
  ElMessageBox.alert('是否要删除该支出对象?', '温馨提示', {
    showCancelButton: true,
    callback: async (action: Action) => {
      if (action == 'confirm') {
        await delDisbursePerson({ id })
        await handleReset()
      }
    },
  })
}
const initData = async (type: initType, page: number) => {

  const params = {
    type: type == 'init' ? '' : queryParams.type,
    cate_name: type == 'init' ? '' : queryParams.cate_name,
    page,
    limit: queryParams.limit,
  }
  await getDisbursePersonList(params)
}
const {
  getDisbursePersonList,
  disbursePersonList,
  delDisbursePerson,
  getDisbursePersonCate,
  addDisbursePerson,
  updateDisbursePerson,
  getDisbursePersonDetail,
} = usePeople()
initData('init', 1)
</script>

<template>
  <main class="bg-white flex flex-col gap-3 rounded-md" style="height: -webkit-fill-available">
    <el-form :model="queryParams" inline>
      <el-form-item label="支出对象身份" style="width: 300px">
        <el-cascader :props="staffProps" v-model="staffName" @change="change" />
      </el-form-item>
      <div class="flex gap-3">
        <formButton @click="handleQuery"> 搜索 </formButton>
        <formButton @click="handleReset"> 重置 </formButton>
        <formButton @click="handleAddPeople"> 添加支出对象 </formButton>
      </div>
    </el-form>
    <el-table
      :data="disbursePersonList?.data"
      border
      header-align="center"
      :header-cell-style="{ background: '#FFF4E5', fontSize: '14px', color: '#888', fontWeight: '400' }"
      @selection-change="handleSelectionChange">
      <el-table-column type="index" label="序号" align="center" width="55" />
      <el-table-column prop="name" label="支出对象姓名" align="center" />
      <el-table-column label="支出对象身份" align="center">
        <template #default="scope">
          {{ scope.row.type + '/' + scope.row.cate_name }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" align="center" />
      <el-table-column label="操作" align="center" width="290">
        <template #default="scope">
          <el-button type="warning" plain size="small" @click="handleEditPeople(scope.row.id)">编辑</el-button>
          <el-button type="danger" plain size="small" @click="handleDelPeople(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleNextPage"
      :current-page="disbursePersonList?.current_page"
      :page-size="queryParams.limit"
      :total="disbursePersonList?.total"
      background
      hide-on-single-page
      class="flex-1 items-end" />
    <el-dialog v-model="peopleDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4 gap-5">
        <NavBar @handleClose="handleClose" :title="dialogType == 'edit' ? '编辑支出对象' : '添加支出对象'" />
        <div style="height: 550px" class="overflow-y-auto">
          <el-form class="px-6 flex flex-col gap-2" label-width="120">
            <el-form-item label="头像:">
              <uploadAvatarImage :modelValue="submitForm.avatar" @finish="handleAvatar" />
            </el-form-item>
            <el-form-item label="名称:" required>
              <el-input v-model="submitForm.name" placeholder="请输入名称" clearable />
            </el-form-item>
            <el-form-item label="身份工种">
              <el-cascader :props="peopleStaffProps" v-model="peopleStaffName" @change="peopleChange" class="flex-1" />
            </el-form-item>
            <el-form-item label="身份证号:">
              <el-input v-model="submitForm.id_card" placeholder="请输入身份证号" clearable type="number" @mousewheel.native.prevent />
            </el-form-item>
            <el-form-item label="手机号:" required>
              <el-input v-model="submitForm.phone" placeholder="请输入手机号" clearable type="number" @mousewheel.native.prevent />
            </el-form-item>
            <el-form-item label="紧急联系人:">
              <el-input v-model="submitForm.exigency_name" placeholder="请输入紧急联系人" clearable />
            </el-form-item>
            <el-form-item label="联系人手机号:">
              <el-input v-model="submitForm.exigency_phone" placeholder="请输入联系人手机号" clearable type="number" @mousewheel.native.prevent />
            </el-form-item>
            <el-form-item label="微信号:">
              <el-input v-model="submitForm.wechat" placeholder="请输入微信号" clearable />
            </el-form-item>
            <el-form-item label="支付宝:">
              <el-input v-model="submitForm.alipay" placeholder="请输入支付宝" clearable />
            </el-form-item>
            <el-form-item label="持卡银行:">
              <el-input v-model="submitForm.bank_name" placeholder="请输入持卡银行" clearable />
            </el-form-item>
            <el-form-item label="银行卡号:">
              <el-input v-model="submitForm.bank_no" placeholder="请输入银行卡号" clearable type="number" @mousewheel.native.prevent />
            </el-form-item>
            <el-form-item label="持卡人:">
              <el-input v-model="submitForm.bank_person" placeholder="请输入持卡人" clearable />
            </el-form-item>
            <el-form-item label="支行名称:">
              <el-input v-model="submitForm.bank_sub" placeholder="请输入支行名称" clearable />
            </el-form-item>
            <el-form-item label="首次合作时间:">
              <el-date-picker
                v-model="showTime"
                type="date"
                placeholder="请选择首次合作时间"
                class="flex-1"
                @change="handleTimeChange" />
            </el-form-item>
            <el-form-item label="合作项目经理:">
              <el-input v-model="submitForm.bank_sub" placeholder="请输入合作项目经理" clearable />
            </el-form-item>
            <el-form-item label="备注:">
              <el-input v-model="submitForm.remark" placeholder="请输入备注" clearable />
            </el-form-item>
          </el-form>
        </div>
        <div class="flex justify-center">
          <div class="save-button" @click="handleSubmit">提交</div>
        </div>
      </div>
    </el-dialog>
  </main>
</template>

<style lang="scss" scoped>
.el-form {
  display: flex;
}
.el-form-item {
  margin-bottom: 0px;
  margin-right: 20px !important;
}

::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}

.save-button {
  @apply text-white px-16 py-3 rounded-md cursor-pointer;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
</style>
